<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------
namespace addon\cms\logic;
use app\common\logic\LogicBase;
use \tpfcore\Core;
use \tpfcore\util\Config;
use think\Db;
use PDO;
/**
 *  帖子逻辑
 */
class Posts extends LogicBase
{
	public function savePosts($data){
		if(isset($data['tag_id']) && is_array($data['tag_id'])){
			$data['tag_id'] = implode(',',$data['tag_id']);
		}
        $validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

		$last_id=Core::loadAddonModel($this->name)->saveObject($data);

		if(empty($data['id']) && !empty(config("config.cms_baidu")) && config("config.cms_baidu")['isauto_submit']==1){
			$submit_url_json = config("config.cms_baidu")['url'];
			$submit_url_json = str_replace('$id', $last_id, $submit_url_json);
			$arr = json_decode($submit_url_json,true);
			$submit_url[] = url($arr['url'],$arr['param']);
			$this->baidu_submit($submit_url);
		}

		if($last_id){
        	return [RESULT_SUCCESS, '操作成功', url('cms/Posts/index')];
        }
	}
	private function baidu_submit($urls){
		$site = config("config.cms_baidu")['site'];
		$token= config("config.cms_baidu")['token'];
		$api = "http://data.zz.baidu.com/urls?site=$site&token=$token";
		$ch = curl_init();
		$options =  array(
		    CURLOPT_URL => $api,
		    CURLOPT_POST => true,
		    CURLOPT_RETURNTRANSFER => true,
		    CURLOPT_POSTFIELDS => implode("\n", $urls),
		    CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		$result = curl_exec($ch);
		return $result;
	}
	public function delPosts($data,$is_delete=false){
		if(is_array($data['id'])){
			$data['id'] = ['in',implode(',',$data['id'])];//批量删除
		}
		return Core::loadAddonModel($this->name)->deleteObject($data,$is_delete,"isdelete")?[RESULT_SUCCESS, '删除成功', url('cms/Posts/index')]:[RESULT_ERROR, '删除失败', url('cms/Posts/index')];
	}
	public function getPostsList($data){
		return self::getList($data);
	}
	public function checkPosts($data){
		if(empty($data)){
			return null;
		}
		if(is_array($data['id'])){
			$arr=[];
			foreach ($data['id'] as $k => $v) {
				$arr[$v]['id']=$v;
				$arr[$v]['ischeck']=(int)$data['ischeck'];
			}
			return self::saveAll($arr)?[RESULT_SUCCESS,'操作成功',url('cms/Posts/index')]:[RESULT_ERROR,'操作失败',url('cms/Posts/index')];
		}
	}
	public function SetTop($data){
		if(empty($data)){
			return null;
		}
		if(is_array($data['id'])){
			$arr=[];
			foreach ($data['id'] as $k => $v) {
				$arr[$v]['id']=$v;
				$arr[$v]['istop']=(int)$data['istop'];
			}
			return self::saveAll($arr)?[RESULT_SUCCESS,'操作成功',url('cms/Posts/index')]:[RESULT_ERROR,'操作失败',url('cms/Posts/index')];
		}
	}
	public function SetRecommend($data){
		if(empty($data)){
			return null;
		}
		if(is_array($data['id'])){
			$arr=[];
			foreach ($data['id'] as $k => $v) {
				$arr[$v]['id']=$v;
				$arr[$v]['isrecommend']=(int)$data['isrecommend'];
			}
			return self::saveAll($arr)?[RESULT_SUCCESS,'操作成功',url('cms/Posts/index')]:[RESULT_ERROR,'操作失败',url('cms/Posts/index')];
		}
	}
	/**
	 * 批量删除或批量更新某个字段
	 * @param  array  $data    ID数组
	 * @param  boolean $is_true 默认为真实删除
	 * @return array|json
	 */
	private function AlldelPosts($data,$is_true=true){
		$Ids = [];
		foreach ($data as $key => $value) {
			$Ids[] = implode(',',$value);
		}
		return Core::loadAddonModel($this->name)->destroy($Ids,$is_true)?[RESULT_SUCCESS,'删除成功',url('cms/Posts/index')]:[RESULT_ERROR,'删除失败',url('cms/Posts/index')];
	}
	/**
	 * 还原/批量还原内容
	 * @param  array  $data    ID inst/array
	 * @return array|json
	 */
	public function restore($data){
		
		$data['id']=is_array($data['id'])?["exp"," in(".implode(",", $data['id']).")"]:$data['id'];

		return self::updateObject($data,["isdelete"=>0])?[RESULT_SUCCESS,'操作成功',url('cms/Recycle/index')]:[RESULT_ERROR,'操作失败',url('cms/Recycle/index')];

	}
	/**
	 * 删除/批量删除内容
	 * @param  array  $data    ID inst/array
	 * @return array|json
	 */
	public function destory($data){
		
		$data['id']=is_array($data['id'])?["exp"," in(".implode(",", $data['id']).")"]:$data['id'];

		return self::deleteObject($data,true)?[RESULT_SUCCESS,'操作成功',url('cms/Recycle/index')]:[RESULT_ERROR,'操作失败',url('cms/Recycle/index')];

	}

	public function move($data){
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene('move')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

        if($data['cateid'] == $data['to_cateid']){
        	return [RESULT_ERROR, "分类一样,移动失败", null];
        }

        $list = $this->getPostsList(["where"=>["cateid"=>$data['cateid']]]);

        if(empty($list)){
        	return [RESULT_ERROR, "没有要移动的文章", null];
        }

        $result = self::updateObject(["cateid"=>$data['cateid']],["cateid"=>$data['to_cateid']]);
        if($result){
        	return [RESULT_SUCCESS, "操作成功,共移动了".count($list)."篇文章", null];
        }else{
        	return [RESULT_ERROR, "操作失败", null];
        } 
	}

	public function wrong($data){
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene('wrong')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

        $action=$data['action'];

        $result = $this->$action();

        return $result;
	}
	public function auto_submit($data){
		$scene=empty($data['type'])?"baidu":$data['type'];
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene($scene)->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

        $urls=parse_url(url("frontend/Index/index"));

        $data['site']=empty($data['site'])?$urls['scheme']."://".$urls['host']:$data['site'];

        $update_config['cms_baidu']=$data;

        Config::updateConfig(ADDON_PATH."cms/config/config.php",$update_config);

        return [RESULT_SUCCESS,"配置成功"];

	}
	private function delete_empty_title(){
		$result = self::deleteObject(['title'=>''],true);
		if($result){
			return [RESULT_SUCCESS, "操作成功", null];
		}
		return [RESULT_ERROR, "没有要操作的文章", null];
	}
	private function delete_empty_content(){
		$result = self::deleteObject(['content'=>''],true);
		if($result){
			return [RESULT_SUCCESS, "操作成功", null];
		}
		return [RESULT_ERROR, "没有要操作的文章", null];
	}
	public function setting($data){
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene("posts_setting")->check($data['configs']);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }
		foreach ($data['configs'] as $key => $value) {
			$update_config[$key]=$value;
		}

		unset($data['configs']);

		Config::updateConfig(ADDON_PATH."cms/config/config.php",$update_config);
		return [RESULT_SUCCESS,"配置成功"];
	}

	// 获取数据库表
	public function getDatabaseTabel(){
		return self::getTables();
	}
	public function getTableFields($data){
		$field = self::getFields($data['field']);
		$field = empty($field)?[]:array_keys($field);
		return [0,"success",$field];
	}
	public function replace($data){
		$validate=Core::addonValidate($this->name);
        $validate_result = $validate->scene("replace")->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $validate->getError(), null];
        }

        $condition=empty($data['condition'])?"":" WHERE ".$data['condition'];

        $table = $data['exptable'];
        $column = $data['column'];
        $rpstring=$data['rpstring'];
        $tostring=$data['tostring'];

        // 普通替换
        if(!empty($data['replace_way']) && $data['replace_way']==1){
        	$sql = "UPDATE $table SET $column=REPLACE($column,'$rpstring','$tostring') $condition";
        	$result = Db::execute($sql);
        	if(empty($result)){
        		return [RESULT_ERROR,"数据替换失败"];
        	}
        	return [RESULT_SUCCESS,"成功替换{$result}条数据"];
        }else{
        	$condition = empty($data['condition']) ? '' : " And ".$data['condition'];
	        $rpstring = stripslashes($rpstring);
	        $rpstring2 = str_replace("\\","\\\\",$rpstring);
	        $rpstring2 = str_replace("'","\\'",$rpstring2);
	        $sql = "SELECT id,$column FROM $table WHERE $column REGEXP '$rpstring2'  $condition";
	        $result = Db::query($sql);
	        if(empty($result)){
	        	return [RESULT_ERROR,"根据你指定的正则，找不到任何东西！"];
	        }
	        $num = 0;
	        $total=count($result);
	        foreach($result as $key=>$val){
	        	$kid=$val['id'];
	        	$rpf = preg_replace("#".$rpstring."#i", $tostring, $column);
	            $rs = Db::execute("UPDATE $table SET $column='$rpf' WHERE id='$kid' ");
	            if($rs)
	            {
	                $num++;
	            }
	        }
	        return [RESULT_SUCCESS,"共找到 $total 条记录，成功替换了 $num 条"];
        }

        



        Db::query("OPTIMIZE TABLE `$table`");

        

	}
}